import { defineStore } from 'pinia'
import { ref, reactive, computed } from 'vue'
import type { TablePaginationConfig } from 'ant-design-vue'
import type { API } from '@/types/api/response'
import type { User, UserQuery, CreateUser, UpdateUser, UserList } from '@/types/api/system/user'
import type { Dept } from '@/types/api/system/dept'
import type { Role } from '@/types/api/system/role'
import type { TransferProps } from 'ant-design-vue'
import dayjs from 'dayjs'
import { 
  getUserList, 
  getUserDetail, 
  createUser, 
  updateUser, 
  deleteUser, 
  resetUserPassword, 
  changeUserStatus, 
  assignRoles 
} from '@/api/system/user'
import { getDeptTree } from '@/api/system/dept'
import { getRoleList } from '@/api/system/role'
import { message } from 'ant-design-vue'
import { useI18n } from 'vue-i18n'

export const useUserStore = defineStore('user', () => {
  const { t } = useI18n()
  
  // ------------ 加载状态 ------------
  const loading = ref(false)
  const submitLoading = ref(false)
  const roleSubmitLoading = ref(false)
  const passwordSubmitLoading = ref(false)
  
  // ------------ 数据列表 ------------
  const userList = ref<User[]>([])
  
  // ------------ 查询参数 ------------
  const queryParams = reactive<UserQuery>({
    keyword: '',
    deptId: undefined,
    status: undefined,
    page: 1,
    pageSize: 10
  })
  
  // ------------ 日期范围 ------------
  const dateRange = ref<[dayjs.Dayjs, dayjs.Dayjs] | undefined>(undefined)
  
  // ------------ 弹窗状态 ------------
  const formModalOpen = ref(false)
  const roleModalOpen = ref(false)
  const passwordModalOpen = ref(false)
  
  // ------------ 表单状态 ------------
  const formMode = ref<'add' | 'edit'>('add')
  const currentId = ref<string>('')
  
  const formData = reactive<{
    username: string;
    nickname: string;
    password: string;
    deptId?: string;
    status: 0 | 1;
    phone: string;
    email: string;
    roleIds: string[];
  }>({
    username: '',
    nickname: '',
    password: '',
    deptId: undefined,
    status: 1,
    phone: '',
    email: '',
    roleIds: []
  })
  
  // ------------ 分页配置 ------------
  const pagination = reactive<TablePaginationConfig>({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true
  })
  
  // ------------ 其他数据 ------------
  const deptTreeData = ref<Dept[]>([])
  const roleOptions = ref<Role[]>([])
  const roleListForTransfer = ref<TransferProps['dataSource']>([])
  const targetRoleIds = ref<string[]>([])
  
  // 重置密码表单
  const passwordForm = reactive<{
    newPassword: string;
    confirmPassword: string;
  }>({
    newPassword: '',
    confirmPassword: ''
  })
  
  // ------------ 计算属性 ------------
  const formTitle = computed(() => formMode.value === 'add' ? t('user.add') : t('user.edit'))
  
  // ------------ 数据操作方法 ------------
  // 获取用户列表
  const fetchUserList = async () => {
    loading.value = true
    try {
      const params: UserQuery = {
        ...queryParams,
        page: pagination.current || 1,
        pageSize: pagination.pageSize || 10
      }
      
      if (dateRange.value) {
        params.dateRange = [
          dateRange.value[0].format('YYYY-MM-DD'),
          dateRange.value[1].format('YYYY-MM-DD')
        ]
      }
      
      const result = await getUserList(params) as API.Response<UserList>
      
      if (result.success) {
        userList.value = result.data.list
        pagination.total = result.data.total
      } else {
        message.error(result.message || t('common.fetchFailed'))
      }
    } catch (error) {
      message.error(t('common.fetchFailed'))
    } finally {
      loading.value = false
    }
  }
  
  // 获取部门树
  const fetchDeptTree = async () => {
    try {
      const res = await getDeptTree()
      if (res.success) {
        deptTreeData.value = res.data
      } else {
        message.error(res.message || t('common.fetchFailed'))
      }
    } catch (error) {
      message.error(t('common.fetchFailed'))
    }
  }
  
  // 获取角色列表
  const fetchRoleList = async () => {
    try {
      const result = await getRoleList({ 
        status: 1,
        page: 1,
        pageSize: 999
      })
      if (result.success) {
        roleOptions.value = result.data.list || []
        roleListForTransfer.value = roleOptions.value.map(role => ({
          key: role.id,
          title: role.roleName,
          description: role.remark || ''
        }))
      } else {
        message.error(result.message || t('common.fetchFailed'))
      }
    } catch (error) {
      message.error(t('common.fetchFailed'))
    }
  }
  
  // 获取用户详情
  const fetchUserDetail = async (id: string) => {
    try {
      const result = await getUserDetail(id)
      if (result.success && result.data) {
        const userData = result.data
        Object.assign(formData, {
          username: userData.username,
          nickname: userData.nickname || '',
          deptId: userData.dept?.id,
          status: userData.status,
          phone: userData.phone || '',
          email: userData.email || '',
          roleIds: userData.roles ? userData.roles.map(role => role.id) : []
        })
        formData.password = ''
      } else {
        message.error(result.message || t('common.fetchDetailFailed'))
      }
    } catch (error) {
      message.error(t('common.fetchDetailFailed'))
    }
  }
  
  // 提交表单
  const submitForm = async () => {
    submitLoading.value = true
    try {
      let result
      if (formMode.value === 'add') {
        const params: CreateUser = {
          username: formData.username,
          password: formData.password,
          nickname: formData.nickname,
          deptId: formData.deptId || '',
          status: formData.status,
          phone: formData.phone,
          email: formData.email,
          roleIds: formData.roleIds
        }
        result = await createUser(params)
      } else {
        const params: UpdateUser = {
          nickname: formData.nickname,
          deptId: formData.deptId || '',
          status: formData.status,
          phone: formData.phone,
          email: formData.email,
          roleIds: formData.roleIds
        }
        result = await updateUser(currentId.value, params)
      }
      
      if (result.success) {
        message.success(formMode.value === 'add' 
          ? t('common.createSuccess') 
          : t('common.updateSuccess')
        )
        formModalOpen.value = false
        fetchUserList()
      } else {
        message.error(result.message || t('common.operationFailed'))
      }
    } catch (error) {
      message.error(t('common.operationFailed'))
    } finally {
      submitLoading.value = false
    }
  }
  
  // 删除用户
  const removeUsers = async (ids: string[]) => {
    try {
      const result = await deleteUser(ids)
      if (result.success) {
        message.success(ids.length > 1 ? t('common.batchDeleteSuccess') : t('common.deleteSuccess'))
        // 如果当前页数据都被删除且不是第一页，则跳转到上一页
        if (ids.length >= userList.value.length && pagination.current && pagination.current > 1) {
          pagination.current -= 1
        }
        fetchUserList()
        return true
      } else {
        message.error(result.message || t('common.deleteFailed'))
        return false
      }
    } catch (error) {
      message.error(t('common.deleteFailed'))
      return false
    }
  }
  
  // 修改用户状态
  const changeStatus = async (userId: string, status: 0 | 1) => {
    try {
      const result = await changeUserStatus(userId, status)
      if (result.success) {
        message.success(t('common.statusChangeSuccess'))
        fetchUserList()
      } else {
        message.error(result.message || t('common.statusChangeFailed'))
      }
    } catch (error) {
      message.error(t('common.statusChangeFailed'))
    }
  }
  
  // 分配角色
  const submitRoles = async () => {
    roleSubmitLoading.value = true
    try {
      const result = await assignRoles(currentId.value, targetRoleIds.value)
      if (result.success) {
        message.success(t('user.assignRolesSuccess'))
        roleModalOpen.value = false
        fetchUserList()
      } else {
        message.error(result.message || t('common.operationFailed'))
      }
    } catch (error) {
      message.error(t('common.operationFailed'))
    } finally {
      roleSubmitLoading.value = false
    }
  }
  
  // 重置密码
  const resetPassword = async (password: string) => {
    passwordSubmitLoading.value = true
    try {
      const result = await resetUserPassword(currentId.value, { 
        password,
        confirmPassword: password 
      }) as unknown as API.Response<void>
      if (result.success) {
        message.success(t('user.resetPasswordSuccess'))
        passwordModalOpen.value = false
      } else {
        message.error(result.message || t('common.operationFailed'))
      }
    } catch (error) {
      message.error(t('common.operationFailed'))
    } finally {
      passwordSubmitLoading.value = false
    }
  }
  
  // ------------ 状态操作方法 ------------
  // 打开表单弹窗
  const openFormModal = async (id?: string) => {
    formMode.value = id ? 'edit' : 'add'
    resetForm()
    if (id) {
      currentId.value = id
      await fetchUserDetail(id)
    }
    formModalOpen.value = true
  }
  
  // 重置表单
  const resetForm = () => {
    Object.assign(formData, {
      username: '',
      nickname: '',
      password: '',
      deptId: undefined,
      status: 1,
      phone: '',
      email: '',
      roleIds: []
    })
    currentId.value = ''
  }
  
  // 重置查询参数
  const resetQuery = () => {
    Object.assign(queryParams, {
      keyword: '',
      deptId: undefined,
      status: undefined,
      page: 1,
      pageSize: 10
    })
    dateRange.value = undefined
    pagination.current = 1
  }
  
  // 处理分页变化
  const handlePageChange = (page: number, pageSize?: number) => {
    pagination.current = page
    if (pageSize) {
      pagination.pageSize = pageSize
    }
    // 重新获取数据
    fetchUserList()
  }

  return {
    // 状态
    loading,
    submitLoading,
    roleSubmitLoading,
    passwordSubmitLoading,
    formModalOpen,
    roleModalOpen,
    passwordModalOpen,
    userList,
    deptTreeData,
    roleOptions,
    roleListForTransfer,
    targetRoleIds,
    pagination,
    queryParams,
    dateRange,
    formData,
    formMode,
    currentId,
    formTitle,
    passwordForm,
    
    // 方法
    fetchUserList,
    fetchDeptTree,
    fetchRoleList,
    fetchUserDetail,
    submitForm,
    removeUsers,
    changeStatus,
    submitRoles,
    resetPassword,
    openFormModal,
    resetForm,
    resetQuery,
    handlePageChange
  }
}) 